package com.kaspersky.gcmconnectivitytest;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.util.Log;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.gson.Gson;

public class GCMIntentService extends GCMBaseIntentService
{
    private SharedPreferences mSettings;
    
    private final static GoogleAnalyticsTracker mTracker = GoogleAnalyticsTracker.getInstance(); 
    
    @Override
    public void onCreate()
    {
        super.onCreate();
        mSettings = getSharedPreferences("fuck.dat", 0);
        
        mTracker.startNewSession("UA-34405719-1", 60 * 60 * 8, this); // each 8 hours
        mTracker.setDebug(true);
    }
    
    @Override
    public void onDestroy()
    {
        mTracker.dispatch();
        super.onDestroy();
    }

    @Override
    protected void onError(Context context, String error)
    {
        // TODO Auto-generated method stub

    }

    final static class DeliveryRequest
    {
        public String message_id;
		public String user_id;
		public int server_time;
        public int connection_type = 0;
    }

    @Override
    protected void onMessage(Context context, Intent intent)
    {
        Log.d("GCMConnectivityTest", "onMessage " + Thread.currentThread().toString());

        final String serverTime  = intent.getStringExtra("server_time");
        final String messageId   = intent.getStringExtra("message_id");
        
        try {
            final String identity = mSettings.getString("user_identity", "Unknown identity"); 
            final DeliveryRequest req = new DeliveryRequest();
            req.message_id  = messageId;
			req.user_id     = identity;
			req.server_time = Integer.parseInt(serverTime);

            try {
                ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                req.connection_type = connMgr.getActiveNetworkInfo().getType();
            }
            catch(Throwable e) {
                req.connection_type = -1;
            }
                
            final String url = "http://ek-gcm-test.appspot.com/delivery_notify";
            final HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            conn.connect();
            conn.getOutputStream().write(new Gson().toJson(req).getBytes());
            
            Log.d("GCMConnectivityTest", "Delivery request: " + new String(new Gson().toJson(req).getBytes()));
            
            final int httpCode = conn.getResponseCode();
            if(httpCode != 200)
                throw new RuntimeException("Non 200 error code");

            byte[] response = new byte[1024];
            if(conn.getInputStream().read(response) < 1)
            	throw new Exception("timeSpent expected");

            final int timeSpent = Integer.parseInt(new String(response));
            
            Log.d("GCMConnectivityTest", "Time spent to deliver: " + timeSpent);
            
            mTracker.trackEvent("Category", identity, "MessageDelivered", timeSpent);
            
            mTracker.trackPageView("/handle_delivery_success");
        }
        catch(Throwable e)
        {
            Log.e("GCMConnectivityTest", e.getMessage(), e);
            mTracker.trackPageView("/handle_delivery_error");
        }
    }

    final static class RegisterRequest
    {
        public String gcm_id;
        public String user_id;
        public int device_time = (int)(new Date().getTime() / 1000);
    }

    private void onRegisteredImpl(Context context, final String regId)
    {
        Log.d("GCMConnectivityTest", "onRegistered " + regId);
        
        try {
            final RegisterRequest req = new RegisterRequest();
            req.gcm_id  = regId;
            req.user_id = mSettings.getString("user_identity", "Unknown identity");
             
            final String url = "http://ek-gcm-test.appspot.com/register_gcm";
            final HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
    
            conn.setDoOutput(true);
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            conn.connect();
            conn.getOutputStream().write(new Gson().toJson(req).getBytes());
            
            final int httpCode = conn.getResponseCode();
            if(httpCode != 200)
                throw new RuntimeException("");
            
            mTracker.trackPageView("/handle_register_success");
        }
        catch(Throwable e)
        {
            Log.e("GCMConnectivityTest", e.getMessage(), e);
            mTracker.trackPageView("/handle_register_error");
        }
    }
    
    @Override
    protected void onRegistered(Context context, final String regId)
    {
        Log.d("GCMConnectivityTest", "onRegistered " + Thread.currentThread().toString());
        onRegisteredImpl(context, regId);
    }

    @Override
    protected void onUnregistered(Context context, String regId)
    {
        // TODO Auto-generated method stub

    }

}
